package com.efuture.collection;

import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

/**
 * @ClassNAME TreeSetTest
 * @Description TreeSet的基本用法
 * @Author zhaoshanshan
 * @Date 2021/9/7 5:01 下午
 * @Version 1.0
 * 无序不可重复 自定义对象需要实现Comparable接口 重写compareTo方法
 */
public class TreeSetTest {

    public static void main(String[] args) {
        //创建对象
        TreeSet treeSet = new TreeSet();
        //添加数据
        treeSet.add("1");
        treeSet.add("2");
        treeSet.add("3");
        treeSet.add("4");
        System.out.println("===========");

        //遍历
        Iterator it = treeSet.iterator();
        while (it.hasNext()){
            Object obj = it.next();
            System.out.println(obj);
        }

        System.out.println("===========");
        TreeSet selfTreeSet = new TreeSet();
        selfTreeSet.add(new SelfTreeSetTestOne(10));
        selfTreeSet.add(new SelfTreeSetTestOne(20));
        selfTreeSet.add(new SelfTreeSetTestOne(5));
        selfTreeSet.add(new SelfTreeSetTestOne(10));
        for(Object obj:selfTreeSet){
            System.out.println(obj);
        }
        System.out.println("===========");
        //匿名内部类实现compare方法
        TreeSet<SelfTreeSetTestTwo> selfTreeSetTwo = new TreeSet<>(new Comparator<SelfTreeSetTestTwo>() {
            @Override
            public int compare(SelfTreeSetTestTwo o1, SelfTreeSetTestTwo o2) {
                return o1.value-o2.value;
            }
        });
        selfTreeSetTwo.add(new SelfTreeSetTestTwo(40));
        selfTreeSetTwo.add(new SelfTreeSetTestTwo(50));
        selfTreeSetTwo.add(new SelfTreeSetTestTwo(30));
        selfTreeSetTwo.add(new SelfTreeSetTestTwo(30));
        for (SelfTreeSetTestTwo selfTreeSetTestTwo:selfTreeSetTwo){
            System.out.println(selfTreeSetTestTwo);
        }
    }
}
class SelfTreeSetTestOne implements Comparable<SelfTreeSetTestOne>{
    private int value;
    public SelfTreeSetTestOne(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return String.valueOf(this.value);
    }

    @Override
    public int compareTo(SelfTreeSetTestOne selfTreeSetTest) {
        return this.value-selfTreeSetTest.value;
    }
}
class SelfTreeSetTestTwo{
    public int value;
    public SelfTreeSetTestTwo(int value) {
        this.value = value;
    }
    @Override
    public String toString() {
        return String.valueOf(this.value);
    }
}